const Controllers = require('../controllers/Controller.js').controller;
const app = getApp();

function InitTime(endtime) {
  var dd, hh, mm, ss = null;
  var time = (new Date(endtime).getTime() - new Date().getTime()) / 1000;
  if (time <= 0) {
    return '结束'
  } else {
    dd = Math.floor(time / 60 / 60 / 24);
    hh = Math.floor((time / 60 / 60) % 24);
    mm = Math.floor((time / 60) % 60);
    ss = Math.floor(time % 60);
    var str = dd + "天" + hh + ":" + mm + ":" + ss;
    return str;
  }
}
Page({
  data: {
    globalStype: '',
    isShow: false,
    goodsId: '',
    goodsDetailsdata: '',
    getShopdata: '',
    getAccountRelationdata: '',
    goodsnumber: 1,
    iscollect: false,
    confirmcartdata: '',
    confirmtype: 'cart',
    cartNum: 0,
    imgheights: [],
    //图片宽度 
    imgwidth: 750,
    //默认  
    current: 0,
    imgList2: [],
    marketid: '',
    marketNo: '',
    backbool: true,
    shareholderPrice: '',
    floatShareholderPrice: '',
    agentPrice: '',
    floatAgentPrice: '',
    couponAccountId: ''
  },
  onLoad: function (option) {
    if (option.scene) {
      // goodsId(商品id),accountId(分享者的用户id),marketId(拼团id),shopId(店铺id)
      const list = decodeURIComponent(option.scene).split(",")
      option = {
        id: list[1],
        invitationAccountId: list[2],
        marketId: list[3],
        shopId :list[4]
      }
    }
    this.setData({
      globalStype: app.globalData.globalStype
    })
    if (option.id) {
      this.setData({
        goodsId: option.id
      })
      this.goodsDetails()
    }
    if (option.writeOff) {
      this.setData({
        writeOff: option.writeOff
      })
    }
    let shopId = ''
    if (app.globalData.shopId) {
      shopId = app.globalData.shopId
    }
    if (option.shopId) {
      shopId = option.shopId
      app.globalData.shopId = option.shopId
      wx.setStorageSync('shopId', shopId)
    }
    if (option.invitationAccountId) {
      this.setData({
        invitationAccountId: option.invitationAccountId
      })
    }
    if (option.couponAccountId) {
      this.setData({
        couponAccountId: option.couponAccountId
      })
    }
    if (wx.getStorageSync('shopId')) {
      shopId = wx.getStorageSync('shopId')
      app.globalData.shopId = shopId
    }
    this.setData({
      shopId,
      getAccountRelationdata: app.globalData.myshopinfo
    })

    if (getCurrentPages().length <= 1) {
      this.setData({
        backbool: false
      })
    } else {
      this.setData({
        backbool: true
      })
    }
  },
  onShow() {
    if (wx.getStorageSync('usertoken')) {
      //加载首页数据
      this.getAccountRelation()
      // this.iscollect() 收藏功能已隐藏
      this.isWriteOff()
      this.cartNum()
      if (this.data.invitationAccountId) {
        this.invitationPerson()
      }
    } else {
      //无usertoken，等待login登录回调
      app.usertokenReadyCallback = res => {
        if (res.data.sessionId) {
          this.getAccountRelation()
          //this.iscollect() 收藏功能已隐藏
          this.isWriteOff()
          this.cartNum()
          if (this.data.invitationAccountId) {
            this.invitationPerson()
          }
        }
      }
    }


  },
  //判断是否为核销商品
  isWriteOff() {
    if (this.data.writeOff) {
      wx.showToast({
        icon: "none",
        title: '请到相关商家去核销商品',
        duration: 2500
      })
    }
  },


  swiperChange: function (e) {
    var that = this;
  },
  getAccountRelation() {
    //获取数据
    Controllers.getAccountRelation({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        getAccountRelationdata: res.data.accountRelation
      })
      app.globalData.myshopinfo = res.data.accountRelation
      wx.setStorageSync('accountId', res.data.id)
    })
  },
  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    console.log(imgwidth, imgheight)
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  bindchange: function (e) {
    // console.log(e.detail.current)
    this.setData({
      current: e.detail.current
    })
  },
  goodsDetails() {
    console.log(this.data.shopId);
    //获取数据
    Controllers.goodsDetails({
      goodsId: this.data.goodsId
    }).then(res => {
      // res.data.rotationImgs=res.data.rotationImgs.split('/')
      if (res.data.labelName)
        res.data.labelName = res.data.labelName.split('/')
      // res.data.detailImgs=res.data.detailImgs.split('/')
      let detail = res.data

      if (detail.price) {
        detail.price2 = (detail.price).toFixed(2)
      } else {
        detail.price2 = (0).toFixed(2)
      }
      if (detail.memberPrice) {
        detail.memberPrice2 = (detail.memberPrice).toFixed(2)
      } else {
        detail.memberPrice2 = (0).toFixed(2)
      }
      if (detail.vipPrice) {
        detail.vipPrice2 = (detail.vipPrice).toFixed(2)
      } else {
        detail.vipPrice2 = (0).toFixed(2)
      }
      if (detail.agentPrice) {
        detail.agentPrice2 = (detail.agentPrice).toFixed(2)
      } else {
        detail.agentPrice2 = (0).toFixed(2)
      }
      if (detail.shareholderPrice) {
        detail.shareholderPrice2 = (detail.shareholderPrice).toFixed(2)
      } else {
        detail.shareholderPrice2 = (0).toFixed(2)
      }
      this.setData({
        goodsDetailsdata: detail,
        price: detail.price2.split(".")[0],
        floatPrice: detail.price2.split(".")[1],
        memberPrice: detail.memberPrice2.split(".")[0],
        floatMemberPrice: detail.memberPrice2.split(".")[1],
        vipPrice: detail.vipPrice2.split(".")[0],
        floatVipPrice: detail.vipPrice2.split(".")[1],
        shareholderPrice: detail.shareholderPrice2.split(".")[0],
        floatShareholderPrice: detail.shareholderPrice2.split(".")[1],
        agentPrice: detail.agentPrice2.split(".")[0],
        floatAgentPrice: detail.agentPrice2.split(".")[1],
      })
      if (this.data.goodsDetailsdata.newPinAccount && this.data.goodsDetailsdata.newPinAccount.endTime) {
        var that = this;
        setInterval(() => {
          this.data.goodsDetailsdata.newPinAccount.downtime = InitTime(this.data.goodsDetailsdata.newPinAccount.endTime.replace(/-/g, '/'))
          this.setData({
            goodsDetailsdata: this.data.goodsDetailsdata
          })

        }, 1000);
      }

      this.getShop()


    })
  },
  getShop() {
    //获取数据
    Controllers.getShop({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        getShopdata: res.data
      })

    })
  },

  cartNum() {
    Controllers.cartNum({
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        cartNumdata: res.data
      })

    })
  },

  calling(e) {
    app.calling(e.currentTarget.dataset.phone)
  },
  onShareAppMessage: function (options) {
    let title = this.data.getShopdata.shopName || '商品详情页';
    // let imageUrl = this.data.goodsDetailsdata.rotationImgs[0] || '';
    let imageUrl = this.data.goodsDetailsdata.shareImg || this.data.goodsDetailsdata.image || '';
    let path = '/pages/Index/Detail?id=' + this.data.goodsId + '&shopId=' + this.data.shopId + "&invitationAccountId=" + this.data.getAccountRelationdata.accountId
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: title,
      path: path,
      imageUrl: imageUrl
    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.name); // shareBtn
      // 此处可以修改 shareObj 中的内容
      // 　　　　shareObj.path = '/pages/btnname/btnname?btn_name='+eData.name;
    }
    // 返回shareObj
    return shareObj;
  },
  plus() {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    var nums = this.data.goodsnumber + 1;
    this.setData({
      goodsnumber: nums
    })
  },
  mins() {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    if (this.data.goodsnumber > 1) {
      var nums = this.data.goodsnumber - 1;
      this.setData({
        goodsnumber: nums
      })
    }
  },
  changenums(e) {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let num = Number(e.detail.value)
    if (!num || num <= 0) num = 1
    this.setData({
      goodsnumber: num
    })
  },
  collect() {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    Controllers.controllerGoods({
      goodsId: this.data.goodsId,
      shopId: this.data.shopId
    }).then(res => {
      this.setData({
        iscollect: res.data
      })
      if (res.data) {
        wx.showToast({
          title: '收藏成功！',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '取消收藏成功！',
          icon: 'none'
        })
      }
    })
  },
  iscollect() {
    Controllers.goodsIsController({
      goodsId: this.data.goodsId
    }).then(res => {
      this.setData({
        iscollect: res.data
      })
    })
  },
  gocart() {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    wx.navigateTo({
      url: '/pages/cart/index/index?isReturn=1'
    })
  },

  gogroup(e) {
    let pin = e.currentTarget.dataset.pin;
    if (pin == 1) {
      this.setData({
        isPin: true
      })
    } else {
      this.setData({
        isPin: false
      })
    }
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let that = this

    // wx.requestSubscribeMessage({
    //   tmplIds:['_uuqoPgxng4xi9Zfhr3xt41_NQrso8WTCUn6M9JoGYs'],
    //   success:res=>{
    //     console.log(res)
    //   },
    //   complete:()=>{
    //     if (!wx.getStorageSync('usertoken')) {
    //       app.ToLoginlink()
    //       return
    //     }

    //     let goods={};
    //     goods=that.data.goodsDetailsdata
    //     goods.shopId=that.data.shopId
    //     goods.goodsId=that.data.goodsId
    //     goods.isPin=that.data.isPin
    //     let marketid=e.currentTarget.dataset.id
    //     that.goodsSettlement(goods,marketid,'')

    //   }
    // })

    if (!wx.getStorageSync('usertoken')) {
      app.ToLoginlink()
      return
    }

    let goods = {};
    goods = that.data.goodsDetailsdata
    goods.shopId = that.data.shopId
    goods.goodsId = that.data.goodsId
    goods.isPin = that.data.isPin
    let marketid = e.currentTarget.dataset.id
    that.goodsSettlement(goods, marketid, '')


    // if(this.data.goodsDetailsdata.type==0){
    //   this.goodsSettlement(goods,marketid,'')
    // }else{
    //   this.setData({
    //     confirmcartdata:goods,
    //     marketid:marketid,
    //     confirmtype:"group",
    //     isShow:true
    //   })
    // }
  },
  gogroupno(e) {
    let pin = e.currentTarget.dataset.pin;
    if (pin == 1) {
      this.setData({
        isPin: true
      })
    } else {
      this.setData({
        isPin: false
      })
    }
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let goods = {};
    goods = this.data.goodsDetailsdata
    goods.shopId = this.data.shopId
    goods.goodsId = this.data.goodsId
    goods.isPin = this.data.isPin
    goods.content = ""
    // goods.num=this.data.goodsnumber
    let marketNo = e.currentTarget.dataset.id
    this.goodsSettlement(goods, '', marketNo)
    // if(this.data.goodsDetailsdata.type==0){
    //   this.goodsSettlement(goods,'',marketNo)
    // }else{
    //   this.setData({
    //     confirmcartdata:goods,
    //     confirmtype:"groupno",
    //     marketNo:marketNo,
    //     isShow:true
    //   })
    // }
  },
  addcart() {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let goods = {};
    goods = this.data.goodsDetailsdata
    goods.shopId = this.data.shopId
    goods.goodsId = this.data.goodsId
    // goods.num=this.data.goodsnumber
    this.setData({
      confirmcartdata: goods,
      isShow: true
    })
  },
  closecart() {
    this.setData({
      isShow: false
    })
  },
  appointment() {
    let that = this
    // wx.requestSubscribeMessage({
    //   tmplIds:['Gc_gkdb1wX-cSBFPD4D5D31w6ZOojJeDckkzo49pBmQ','FKMu-6I96hfuWhGpwb-JxdAKmtI1j013G4GTy2rz7Ms','hD6D4MmAd2JDgrivAhrWDoOXweER5uf9ONSwryEXVe0'],
    //   success:res=>{
    //     console.log(res)
    //   },
    //   complete:()=>{
    //     if (!wx.getStorageSync('usertoken')) {
    //       app.GetLogin()
    //       return
    //     }
    //     if(that.data.getAccountRelationdata.vip==0 && that.data.goodsDetailsdata.vip==1){
    //       wx.showToast({
    //         title: 'VIP专享，请注册为会员！',
    //         icon: 'none'
    //       })
    //     }else{
    //       wx.navigateTo({
    //         url:'/pages/Index/Service?id='+that.data.goodsId
    //       })
    //     }
    //   }
    // })

    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    if (that.data.getAccountRelationdata.vip == 0 && that.data.goodsDetailsdata.vip == 1) {
      wx.showToast({
        title: 'VIP专享，请注册为会员！',
        icon: 'none'
      })
    } else {
      wx.navigateTo({
        url: '/pages/Index/Service?id=' + that.data.goodsId
      })
    }
  },
  confirmcart(e) {
    let pin = e.currentTarget.dataset.pin;
    if (pin == 1) {
      this.setData({
        isPin: true
      })
    } else {
      this.setData({
        isPin: false
      })
    }
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let goods = this.data.confirmcartdata;
    goods.num = this.data.goodsnumber
    goods.isPin = this.data.isPin
    if (this.data.confirmtype == 'group') {
      this.goodsSettlement(goods, this.data.marketid, '')
    } else if (this.data.confirmtype == "groupno") {
      this.goodsSettlement(goods, '', this.data.marketNo)
    } else {
      this.addGoods(goods)
    }
  },
  goodsSettlement(goods, marketid, marketNo) {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    var goods = goods;
    delete goods.content;
    if (this.data.getAccountRelationdata.vip == 0 && this.data.goodsDetailsdata.vip == 1) {
      wx.showToast({
        title: 'VIP专享，请注册为会员！',
        icon: 'none'
      })
    } else {
      if (marketid) {
        let data = {
          shopId: this.data.shopId,
          goodsId: this.data.goodsId,
          marketId: marketid
        }

        Controllers.createMarket(data).then(res => {
          let no = res.data.no
          console.log(goods)

          wx.navigateTo({
            url: '/pages/cart/submitOrder/submitOrder?good=' + encodeURIComponent(JSON.stringify(goods)) + '&isGood=true&marketNo=' + no
          })
        })
      } else if (marketNo) {
        let no = marketNo
        console.log(goods)
        wx.navigateTo({
          url: '/pages/cart/submitOrder/submitOrder?good=' + encodeURIComponent(JSON.stringify(goods)) + '&isGood=true&marketNo=' + no
        })
      } else {
        console.log(goods)
        wx.navigateTo({
          url: '/pages/cart/submitOrder/submitOrder?good=' + encodeURIComponent(JSON.stringify(goods)) + '&isGood=true' + '&couponAccountId=' + this.data.couponAccountId,
        })
      }

    }
  },
  goorder(e) {
    let pin = e.currentTarget.dataset.pin;
    if (pin == 1) {
      this.setData({
        isPin: true
      })
    } else {
      this.setData({
        isPin: false
      })
    }
    let that = this
    // wx.requestSubscribeMessage({
    //   tmplIds:['_uuqoPgxng4xi9Zfhr3xt41_NQrso8WTCUn6M9JoGYs'],
    //   success:res=>{
    //     console.log(res)
    //   },
    //   complete:()=>{
    //     if (!wx.getStorageSync('usertoken')) {
    //       app.GetLogin()
    //       return
    //     }
    //     let goods={};
    //     goods=that.data.goodsDetailsdata
    //     goods.shopId=that.data.shopId
    //     goods.goodsId=that.data.goodsId
    //     goods.isPin=that.data.isPin
    //     goods.num=that.data.goodsnumber
    //     console.log(goods);
    //     that.goodsSettlement(goods,'','')
    //   }
    // })

    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    let goods = {};
    goods = that.data.goodsDetailsdata
    goods.shopId = that.data.shopId
    goods.goodsId = that.data.goodsId
    goods.isPin = that.data.isPin
    goods.num = that.data.goodsnumber
    console.log(goods);
    that.goodsSettlement(goods, '', '')
  },
  addGoods(data) {
    if (!wx.getStorageSync('usertoken')) {
      app.GetLogin()
      return
    }
    if (this.data.getAccountRelationdata.vip == 0 && this.data.goodsDetailsdata.vip == 1) {
      wx.showToast({
        title: 'VIP专享，请注册为会员！',
        icon: 'none'
      })
    } else {
      let goods = this.data.goodsDetailsdata;
      let data = {}
      data.goodsId = goods.goodsId;
      data.num = this.data.goodsnumber;
      data.shopId = goods.shopId;
      Controllers.addGoods(data).then(res => {
        wx.showToast({
          title: '加入购物车成功！',
          icon: 'none',
          duration: 1000
        })
        this.setData({
          isShow: false
        })
      })
    }
  },

  preview(event) {
    let currentUrl = event.currentTarget.dataset.src
    let lists = []
    for (let item of event.currentTarget.dataset.lists) {
      lists.push(item.image)
    }
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: lists // 需要预览的图片http链接列表
    })
  },
  backindex(e) {
    let page = getCurrentPages()
    let shopId = this.data.shopId
    console.log(page.length)
    if (page.length <= 1) {
      wx.redirectTo({
        url: '/pages/Index/Index?shopId=' + shopId,
      })
    }
  },

  //绑定上级
  invitationPerson() {
    let value = {}
    value.invitationAccountId = this.data.invitationAccountId
    value.shopId = wx.getStorageSync('shopId')
    Controllers.invitationPerson(value).then(res => {

    })
  },
  //生成海报图
  sharePoster() {
    let value = {}
    value.marketId = this.data.goodsDetailsdata.marketList[0].id
    Controllers.sharePinGoods(value).then(res => {
      // 加时间戳防止缓存问题，打开图片不完整
      let timestamp = Date.parse(new Date())
      let img = res.data + "?t=" + timestamp
      let list = []
      list.push(img)
      wx.previewImage({
        urls: list,
      })
    })
  },
  //去店铺
  toShop() {
    wx.redirectTo({
      url: '/pages/Index/Index',
    })
  },

  //  跳转播放视频页
  toVideoPage() {
    const data = {
      video: this.data.goodsDetailsdata.video,
      videoDesc: this.data.goodsDetailsdata.videoDesc || '',
      img: this.data.goodsDetailsdata.img || this.data.goodsDetailsdata.image,
      name: this.data.goodsDetailsdata.name,
    }
    wx.navigateTo({
      url: '/pages/TradingArea/videoPlay?data=' + JSON.stringify(data),
    })
  },
})